#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDateTime>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle("温湿度波形分析v1.0"); //设置标题
    udp_init();
    ui_init();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::udp_init()
{
    m_Socket = new QUdpSocket();
}

void MainWindow::ui_init()
{
    m_wave = new wave(this);
    m_wave1 = new wave(this);
    m_wave2 = new wave(this);
//    m_wave->setGeometry(ui->graphicsView->x(),ui->graphicsView->y(),600,600);
    //udp 控件初始
    QStringList ipList,portList;
    ipList<<"192.168.137.1"<<"无"; //ip地址
    portList<<"8888"<<"7777";  //port端口号
    ui->comboBox_ip->addItems(ipList);
    ui->comboBox_port->addItems(portList);
    // 微调框
    int nMin =0;
    int nMax =100;
    int nSingleStep =10;
     ui->spinBox->setMinimum(nMin);  // 最小值
     ui->spinBox->setMaximum(nMax);  // 最大值
     ui->spinBox->setSingleStep(nSingleStep);  // 步长
    // 滑动条
     ui->horizontalSlider ->setMinimum(nMin);  // 最小值
     ui->horizontalSlider ->setMaximum(nMax);  // 最大值
     ui->horizontalSlider ->setSingleStep(nSingleStep);  // 步长
    // 连接信号槽（相互改变）
    connect( ui->spinBox_2, SIGNAL(valueChanged(int)), ui->horizontalSlider, SLOT(setValue(int)));
    connect( ui->horizontalSlider, SIGNAL(valueChanged(int)),ui->spinBox_2, SLOT(setValue(int)));
    ui->spinBox_2->setValue(50);
    ui->spinBox_2->setMinimum(nMin);  // 最小值
    ui->spinBox_2->setMaximum(nMax);  // 最大值
    ui->spinBox_2->setSingleStep(nSingleStep);  // 步长
   // 滑动条
    ui->horizontalSlider_2 ->setMinimum(nMin);  // 最小值
    ui->horizontalSlider_2 ->setMaximum(nMax);  // 最大值
    ui->horizontalSlider_2 ->setSingleStep(nSingleStep);  // 步长
   // 连接信号槽（相互改变）
    connect( ui->spinBox, SIGNAL(valueChanged(int)), ui->horizontalSlider_2, SLOT(setValue(int)));
    connect( ui->horizontalSlider_2, SIGNAL(valueChanged(int)),ui->spinBox, SLOT(setValue(int)));
    ui->spinBox->setValue(50);
    m_wave->setTitle("温度波形图");
    m_wave1->setTitle("湿度波形图");
    m_wave2->setTitle("光照波形图");
    m_tabWidget = new QTabWidget(this);
    m_tabWidget->addTab(m_wave,"温度");
    m_tabWidget->addTab(m_wave1,"湿度");
    m_tabWidget->addTab(m_wave2,"光照");
    m_tabWidget->setGeometry(25,240,400,300);

    this->setAutoFillBackground(true);
    QPalette palette;
    QPixmap pixmap(":/new/prefix1/background.jpg");
    palette.setBrush(QPalette::Window, QBrush(pixmap));
    this->setPalette(palette);
    ui->start->hide();
//    ui->comboBox->hide(); //隐藏选择节点
}


void MainWindow::on_updlink_clicked()
{
    QString ip = ui->comboBox_ip->currentText();
    QString port = ui->comboBox_port->currentText();
    //判断连接
  if(m_Socket->bind(QHostAddress(ip),port.toInt())) {
        ui->infomess->append("成功连接");
        connect(m_Socket,SIGNAL(readyRead()),this,SLOT(read_data()));
  }
  else {
      QString mess = "ip:"+ip+" 端口号:"+port+"\n 未成功连接:\n";
       ui->infomess->append(mess);
  }
}


void MainWindow::read_data()
{
     QByteArray array;
     array.resize(m_Socket->bytesAvailable());//根据可读数据来设置空间大小
     m_Socket->readDatagram(array.data(),array.size(),&address,&port); //读取数据
     QString str;
     str.append(array);
     QStringList list = str.split("#");
     QDateTime now_time =QDateTime::currentDateTime();
      //设置时间格式
     QString time =now_time.toString("yyyy-MM-dd hh:mm:ss dddd");
     QString mess = "温度："+list[0]+ "\t湿度："+list[1]+ "\t光照："+list[2]+ "\n时间："+time;
     ui->listWidget->addItem(mess);//显示数据
     ui->listWidget->scrollToBottom(); //滑动到底

     if (m_Node_Lenth == 0) {
         //波形处理
         m_wave->set_value(list[0].toFloat());
         m_wave1->set_value(list[1].toFloat());
         m_wave2->set_value(list[2].toFloat());
     }
     else {
        if(ui->comboBox->currentText() == QString::number(port)) {
            //波形处理
            m_wave->set_value(list[0].toFloat());
            m_wave1->set_value(list[1].toFloat());
            m_wave2->set_value(list[2].toFloat());
        }
     }
     isaddress = true;
//     readPendingDatagrams();
     QString firstData ="IP:"+ address.toString() + "\nPort:" + QString::number(port);
     if (m_Node_Lenth == 0) {
         m_Node[0]=QString::number(port);
         m_Node_Lenth++;
     }
     else if(m_Node_Lenth == 1){
         if(m_Node[0]!=QString::number(port)) {
            m_Node[1]=QString::number(port);
            m_Node_Lenth++;
         }

     }
     ui->textEdit->setText(firstData);
     if(m_Node_Lenth == 1) {
        ui->comboBox->clear();
        ui->comboBox->addItem(m_Node[0]);
     }
     if(m_Node_Lenth == 2) {
        ui->comboBox->clear();
        ui->comboBox->addItem(m_Node[0]);
        ui->comboBox->addItem(m_Node[1]);
        m_Node_Lenth++;
     }


}

void MainWindow::on_pushButton_4_clicked()
{
    delete  m_Socket;
     ui->infomess->clear();
    ui->infomess->append("成功断开连接");
    m_Socket = new QUdpSocket();
    ui->comboBox->clear();
    m_Node[0]="";
    m_Node[1]="";
}



void MainWindow::on_start_clicked()
{
    QString str = "23.5#75.5#50";
    QStringList list = str.split("#");
    QDateTime now_time =QDateTime::currentDateTime();
       //设置时间格式
    QString time =now_time.toString("yyyy-MM-dd hh:mm:ss dddd");
    QString mess = "温度："+list[0]+ "\t湿度："+list[1]+ "\t光照："+list[2]+ "\n时间："+time;
    ui->listWidget->addItem(mess);//显示数据
    //波形处理
    m_wave->set_value(list[0].toFloat());
    m_wave1->set_value(list[1].toFloat());
}

void MainWindow::readPendingDatagrams()
{
    qDebug() << "readPendingDatagrams called!";
       while(m_Socket->hasPendingDatagrams()){

           QHostAddress srcAddress;
           quint16 nSrcPort;
           QByteArray datagram;
           datagram.resize(m_Socket->pendingDatagramSize());
           m_Socket->readDatagram(datagram.data(), datagram.size(), &srcAddress, &nSrcPort);;
           QString firstData = srcAddress.toString() + " " + QString::number(nSrcPort) + " :";
           ui->textEdit->setText(firstData);
       }
      qDebug() << "end!";

}

//温度#湿度#flag#flag

void MainWindow::on_pushButton_clicked()
{
    //温度
   int warm = ui->spinBox_2->value();
     //湿度
   int humidity = ui->spinBox->value();
   QByteArray array;
   QString str; //构造
   str += QString::number(warm);
   str += "#";
   str += QString::number(humidity);
   array = str.toUtf8();
    if(isaddress) {
        if(m_Node_Lenth == 0) {
           m_Socket->writeDatagram(array,address,port);
        }
        else {
           m_Socket->writeDatagram(array,address,ui->comboBox->currentText().toUShort());
        }
    }
    qDebug() << array;
}
